package com.baijia.web.controller.v1;

import com.baijia.dao.po.Passport;
import com.baijia.services.PassportService;
import com.baijia.web.config.PassportConfig;
import com.baijia.web.controller.AbstractAuthorizeController;
import com.baijia.web.dto.response.BaseResponse;
import com.baijia.web.util.URLUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/v1")
public class AccountController extends AbstractAuthorizeController {

    // private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PassportConfig passportConfig;

    @Resource
    private PassportService passportService;

    @RequestMapping(value = "index")
    @ResponseBody
    public BaseResponse login(HttpServletRequest request) {
        BaseResponse res = new BaseResponse();
        res.setMsg("hello");
        res.setStatus(1);
        return res;
    }

    @RequestMapping(value = "/reg")
    public String register() throws IOException {
        return "reg";
    }

    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public String register(Passport passport, Model model) throws IOException {
        if (!passportService.existedUser(passport.getMobile(), 0)) {
            model.addAttribute("errInfo", "手机号码已经被注册.");
            return "reg";
        }
        if (passportService.createAccount(passport) > 0) {
            String loginUrl =
                URLUtil.getLoginUrl(passport.getMobile(), passport.getPassword(), passportConfig.getLoginUrl());
            return "redirect:" + loginUrl;
        } else {
            model.addAttribute("errInfo", "注册发生系统错误,请联系管理员.");
            return "reg";
        }

    }

    @RequestMapping(value = "/updatePwd")
    public BaseResponse updatePwd(HttpServletRequest request) {
        BaseResponse res = new BaseResponse();
        res.setMsg("hello");
        res.setStatus(1);
        return res;
    }

    @RequestMapping(value = "/forgetPwd")
    public BaseResponse forgetPwd(HttpServletRequest request) {
        BaseResponse res = new BaseResponse();
        res.setMsg("hello");
        res.setStatus(1);
        return res;
    }

}
